package com.ymk.cmd;


import com.ymk.base.cmd.ACmd;
import com.ymk.base.cmd.CmdSign;
import com.ymk.base.exception.MallException;
import com.ymk.base.utlis.ParamsBuilder;
import com.ymk.bo.rbac.RbacRoleBO;
import com.ymk.bo.rbac.RbacUserRoleBO;
import com.ymk.core.code.cmd.RbacCmdCode;
import com.ymk.service.IRbacUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Service
public class RbacUserRolePostCmd extends ACmd {

    @Override
    public CmdSign executeSop(HttpServletRequest request, CmdSign sign) throws Exception {
        CmdSign respSign = new CmdSign(sign);
        RbacRoleBO rbacRoleBO = super.getData(sign, RbacRoleBO.class);
        super.setCreatedData(sign,rbacRoleBO);

        return respSign;
    }

    @Override
    public CmdSign executeMop(HttpServletRequest request, CmdSign sign) throws Exception {
        CmdSign respSign = new CmdSign(sign);
        RbacUserRoleBO repData  = super.getData(sign,RbacUserRoleBO.class);


        ParamsBuilder paramsBuilder = ParamsBuilder.newBuild()
                .addParam("roleId",repData.getRoleId())
                .addParam("mchId",repData.getMchId())
                .addParam("userId",repData.getUserId());

        RbacUserRoleBO rbacUserRoleBO = this.rbacRoleUserService.get(paramsBuilder.build());

        if (!Objects.isNull(rbacUserRoleBO)){
            throw new MallException("该角色已为用户分配");
        }
        RbacUserRoleBO rbacUserRole = new RbacUserRoleBO();
        // 组装用户角色对应关系
        rbacUserRole.setMchId(repData.getMchId());
        rbacUserRole.setUserId(repData.getUserId());
        rbacUserRole.setRoleId(repData.getRoleId());
        rbacUserRole.setDeleted(1);
        this.rbacRoleUserService.post(rbacUserRole);

        respSign.setSource(super.getSource(rbacUserRole));
        return respSign;
    }


    @Override
    public String getCmdCode() {
        return RbacCmdCode.RBAC_USER_ROLE_POST;
    }

    @Autowired
    private IRbacUserRoleService rbacRoleUserService;

}
